package com.tl.commonlibrary.ui.widget;

import android.content.Context;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tl.commonlibrary.R;
import com.tl.commonlibrary.tool.DeviceUtil;

/**
 * Created by a on 2015/11/12.
 */
public class NetErrorView extends LinearLayout implements View.OnClickListener {
    private TextView contentView;
    private OnNetErrorClickListener netErrorClickListener;

    public NetErrorView(Context context) {
        this(context, null);
    }

    public NetErrorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        setLayoutParams(params);
        setOrientation(VERTICAL);
        setGravity(Gravity.CENTER);
        contentView = new TextView(context);
        LayoutParams txtParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        contentView.setLayoutParams(txtParams);
        contentView.setGravity(Gravity.CENTER);
        String bigText = "网络请求失败";
        String smallText = "\n点击重新加载";
        contentView.setTextSize(DeviceUtil.px_to_sp((int) getResources().getDimension(R.dimen.font_hint_small), context));
        contentView.setTextColor(getResources().getColor(R.color.font_hint_small));
        contentView.setLineSpacing(15, 1);
        SpannableString ss = new SpannableString(bigText + smallText);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_999999)), 0, bigText.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        ss.setSpan(new AbsoluteSizeSpan((int) getResources().getDimension(R.dimen.font_hint_big)), 0, bigText.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        contentView.setText(ss);
        contentView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_net_error, 0, 0);
        contentView.setCompoundDrawablePadding((int) getResources().getDimension(R.dimen.spacing_30px));
        addView(contentView);
        contentView.setOnClickListener(this);

    }

    public void setOnLoadFailedClickListener(OnNetErrorClickListener failedClickListener) {
        this.netErrorClickListener = failedClickListener;
    }

    @Override
    public void onClick(View v) {
        if (v == contentView) {
            if (netErrorClickListener != null) {
                netErrorClickListener.onNetErrorClicked();
            }
        }
    }

    public interface OnNetErrorClickListener {
        void onNetErrorClicked();
    }

}
